<?php
	DEFINE('H1', '7-4: Building a Login Form');
	DEFINE('TITLE','7-4: Building a Login Form');
	require('includes/header.php');
?>	
	<h2><?PHP echo H1 ?></h2>

<?php
	if(!isset($_POST['submit'])) {
?>
	<form method="post" action="login.php">
		Username: <br />
		<input type="text" name="username" />
		<br />
		Password: <br />
		<input type="password" name="password" />
		<br /><br />
		
		<input type="submit" name="submit" value="Log In" />	
	</form>
<?php
	} else {
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		if (empty($username)) {
			die('Error: Please enter your username');
		}
		if (empty($password)) {
			die('Error: Please enter your password');
		}
		
		require_once ('db/DBParms.php');

		$mysqli = new  mysqli(DBHOST, DBUSER, DBPWD, "appl");
			if($mysqli === false) {
				die("Error: Could not connect to database . " . mysqli_connect_error());
			}

		$username = $mysqli->escape_string($_POST['username']);
		
		$sql = "SELECT username FROM users WHERE username = '$username'";
		if ($result = $mysqli->query($sql)) {
			$row = $result->fetch_object();
			
			if ($result->num_rows > 0) {
				$sql = "SELECT password FROM users WHERE username = '$username'";
				
				if ($result = $mysqli->query($sql)) {
					$row = $result->fetch_object();
					$salt = $row->password;
					if ($salt == sha1($_POST['password'])) {
						echo 'Your login credentials were successfully verified.';
					} else {
						echo 'You entered an incorrect password.';
					}
				} else {
					echo "Error: Could not execute $sql . " . $mysqli->error;
				}
			} else {
				echo 'You entered an incorrect username.';
			}
		} else {
			echo "Error: Could not execute $sql. " . $mysqli->error;
		}
	$mysqli->close();
	}	

?>

<?php
	require('includes/footer.php');
?>